package com.ccteam.fluidmusic.ui.local.tag

import android.os.Bundle
import android.text.format.DateUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import com.ccteam.fluidmusic.R
import com.ccteam.fluidmusic.databinding.DialogLocalMusicTagBinding
import com.ccteam.taglib.core.MediaTag
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import dagger.hilt.android.AndroidEntryPoint

/**
 * @author Xiaoc
 * @since 2021/4/9
 */
@AndroidEntryPoint
class LocalMusicTagFragment: BottomSheetDialogFragment() {

    private var _binding: DialogLocalMusicTagBinding? = null
    private val binding get() = _binding!!

    private val localMusicTagViewModel by viewModels<LocalMusicTagViewModel>()

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = DialogLocalMusicTagBinding.inflate(inflater,container,false)
        return binding.root
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        localMusicTagViewModel.mediaTagInfo.observe(viewLifecycleOwner, {
            updateTagInfo(it)
        })

        binding.btnEditTag.setOnClickListener {
            localMusicTagViewModel.mediaUri.value?.let {
                findNavController().navigate(
                    LocalMusicTagFragmentDirections.actionLocalMusicTagFragmentToLocalMusicTagEditFragment(
                        it
                    )
                )
            }

        }
    }

    private fun updateTagInfo(tag: MediaTag) = with(binding){
        tvDescription.text = getString(
            R.string.description_tag_description,tag.length,
            DateUtils.formatElapsedTime(tag.length.toLong()),
            tag.sampleRate,tag.bitrate,tag.size)
        tvTitle.text = tag.title
        tvCopyright.text = tag.copyright
        tvTrack.text = tag.track.toString()
        tvDisc.text = tag.disc.toString()
        tvYear.text = tag.year.toString()
        tvGenre.text = tag.genre
        tvArtist.text = tag.artist
        tvAlbum.text = tag.album
        tvAlbumArtist.text = tag.albumArtist
        tvComposer.text = tag.composer
        tvComment.text = tag.comment
    }

    override fun onDestroyView() {
        super.onDestroyView()

        _binding = null
    }
}